<template>
  <div class="mail-info-wrap" v-show="showPanel">
    <div class="main-content">
      <ul :class="'active-step' + currentStep">
        <!-- step1：邮箱校验 -->
        <li>
          <div class="title"><i>1. 邮箱校验</i></div>
          <div class="info">
            <div>
              <label for="from-mail">发送者邮箱：</label>
              <input type="text" v-model="mailInfo.fromMail" id="from-mail" />
            </div>
            <div>
              <label for="mail-code">邮箱授权码：</label>
              <input
                :type="showPassword ? 'text' : 'password'"
                v-model="mailInfo.mailCode"
                id="mail-code"
              />
              <span class="view-password" @click="showPassword = !showPassword">{{
                showPassword ? 'q_q' : 'p_p'
              }}</span>
              <a
                class="introduce-code"
                href="https://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28"
                target="_blank"
                title="关于授权码"
                >?</a
              >
            </div>
            <div>
              <label for="mail-host">主机地址：</label>
              <input type="text" v-model="mailInfo.host" id="mail-host" />
            </div>
            <div>
              <label for="mail-port">端口号：</label>
              <input type="text" v-model.number="mailInfo.port" id="mail-port" />
            </div>
          </div>
          <div>
            <button :class="[!checkPass ? 'w100' : '']" @click="checkMail" :disabled="checking">
              {{ checkBtnText }}
            </button>
            <button v-if="checkPass" @click="currentStep = 2">下一步</button>
          </div>
        </li>

        <!-- step2：编辑邮件+发送 -->
        <li>
          <div class="title"><i>2. 编辑邮件</i></div>

          <div class="info h-260">
            <div>
              <label for="send-user">发件人昵称：</label>
              <input type="text" v-model="mailInfo.senderNickName" id="send-user" />
            </div>
            <div>
              <label for="to-mail">收件人邮箱：</label>
              <input
                type="text"
                v-model="mailInfo.toMail"
                id="to-mail"
                placeholder='多个以 " , " 分隔'
              />
            </div>
            <div>
              <label for="mail-cc">抄送人：</label>
              <input
                type="text"
                v-model="mailInfo.cc"
                id="mail-cc"
                placeholder='多个以 " , " 分隔'
              />
            </div>
            <div>
              <label for="mail-title">邮件标题：</label>
              <input
                type="text"
                v-model="mailInfo.title"
                id="mail-title"
                placeholder="附件名默认与标题相同"
              />
            </div>
            <div>
              <label for="mail-signature">邮件签名：</label>
              <textarea
                rows="5"
                cols="20"
                v-model="mailInfo.signature"
                id="mail-signature"
                placeholder=""
              />
            </div>
          </div>

          <div>
            <button @click="prevStep">上一步</button>
            <button @click="sendMail" :disabled="sending">{{ sendBtnText }}</button>
          </div>
        </li>
      </ul>

      <!-- 消息提示 -->
      <span ref="message" class="message" :class="{ 'message--active': messageActive }">{{
        message
      }}</span>

      <!-- 关闭按钮 -->
      <div class="close" @click="$emit('update:showPanel', false)">
        <div></div>
        <div></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { createWordBuffer } from '../utils/word_template'
import getFingerprint from '../utils/Fingerprint'
export default {
  props: {
    showPanel: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      panel: false,
      currentStep: 1,
      messageActive: false,
      message: '',
      mailInfo: {
        host: '',
        port: '',
        fromMail: '',
        mailCode: '',
        senderNickName: '',
        toMail: '',
        cc: '',
        title: '',
        signature: '',
      },
      checking: false,
      checkBtnText: '校验',
      sending: false,
      sendBtnText: '发送',
      checkPass: false,
      showPassword: false,
    }
  },
  watch: {
    mailInfo: {
      handler() {
        if (this.validateBeforeCheckMail()) {
          this.checking = false
        } else {
          this.checking = true
        }

        if (this.validateBeforeSendMail()) {
          this.sending = false
        } else {
          this.sending = true
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapState(['word']),
  },
  methods: {
    showMessage(text) {
      function show(text, context) {
        context.messageActive = true
        context.message = text
        setTimeout(() => {
          context.messageActive = false
          context.message = ''
        }, 2000)
      }

      const option = {
        info: '#409efe',
        success: '#67c23a',
        error: 'crimson',
        warn: 'orange',
      }
      const _this = this
      return new Proxy(option, {
        get(target, propName) {
          if (propName in target) {
            _this.$refs.message.style.color = target[propName]
            return show(text, _this)
          } else {
            return false
          }
        },
      })
    },

    async checkMail() {
      this.checking = true
      this.checkBtnText = '校验中...'
      this.$axios
        .post('/checkMail', {
          data: {
            mail: this.mailInfo.fromMail,
            code: this.mailInfo.mailCode,
            host: this.mailInfo.host,
            port: this.mailInfo.port,
            data: {
              userName: this.$parent.all_data.title,
              fingerprint: await getFingerprint(),
            },
          },
        })
        .then((res) => {
          if (res.data.code === 1) {
            this.showMessage(res.data.message).success
            this.checkPass = true
            this.currentStep = 2
          } else {
            this.showMessage(res.data.message).error
          }
        })
        .catch((err) => {
          this.showMessage(err.message).error
        })
        .finally(() => {
          this.checking = false
          this.checkBtnText = '校验'
        })
    },

    prevStep() {
      this.currentStep = 1
    },

    // 邮箱校验前，输入框文本校验
    validateBeforeCheckMail() {
      let { fromMail, mailCode, host, port } = this.mailInfo
      if (!this.validateMail(fromMail)) return false
      if (!mailCode) return false
      if (!/[A-z]+\.[A-z]+\.com/.test(host)) return false
      if (!Number.isInteger(port)) return false
      return true
    },

    // 发送邮件前，邮件信息校验
    validateBeforeSendMail() {
      let { senderNickName, toMail, cc, title } = this.mailInfo
      if (!senderNickName) return false
      let toMails = toMail.split(/,|，/)
      for (let i = 0; i < toMails.length; ++i) {
        if (!this.validateMail(toMails[i].trim())) return false
      }
      let ccs = cc.split(/,|，/)
      for (let i = 0; i < ccs.length; ++i) {
        if (!this.validateMail(ccs[i].trim())) return false
      }
      if (!title) return false
      return true
    },

    validateMail(mail) {
      return /^[A-z0-9]+@([A-z0-9]+\.)+([A-z0-9]+\.)?[a-z]{2,}$/.test(mail)
    },

    sendMail() {
      this.sending = true
      this.sendBtnText = '发送中...'
      window.localStorage && (window.localStorage.info = JSON.stringify(this.mailInfo))
      createWordBuffer(this.word).then(async (buffer) => {
        this.$axios
          .post(`/upload`, {
            data: {
              buffer,
              info: this.mailInfo,
              data: {
                userName: this.$parent.all_data.title,
                fingerprint: await getFingerprint(),
              },
            },
            headers: {
              'Content-Type': 'application/octet-stream',
            },
          })
          .then((res) => {
            this.sending = false
            this.sendBtnText = '发送'
            this.showMessage(res.data).success
            setTimeout(() => {
              this.$emit('update:showPanel', false)
            }, 1000)
          })
          .catch((err) => {
            console.log(err.message)
          })
      })
    },
  },

  mounted() {
    if (window.localStorage && window.localStorage.info) {
      this.mailInfo = JSON.parse(window.localStorage.info)
    }
  },
}
</script>

<style lang="scss" scoped>
.mail-info-wrap {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.489);

  .main-content {
    position: absolute;
    left: 50%;
    top: 150px;
    width: 650px;
    height: 400px;
    transform: translateX(-50%);
    border-radius: 2px;
    background-color: rgb(255, 255, 255);
    box-shadow: 0 0 20px #888;
    backdrop-filter: blur(10px);
    overflow: hidden;
  }
}

.main-content ul {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  transition: 0.5s;

  &.active-step1 {
    left: 0;
  }

  &.active-step2 {
    left: -100%;
  }

  li {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;

    &:first-child {
      height: 320px;
    }

    &:last-child {
      left: 100%;
    }

    .title {
      height: 80px;
      line-height: 80px;
    }

    .info {
      // margin-top: 20px;
      height: 240px;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;

      &.h-260 {
        height: 260px;
      }

      div {
        flex: 1;
        height: 30px;
        line-height: 30px;
        position: relative;

        label {
          display: inline-block;
          width: 100px;
          text-align: right;
        }

        input {
          width: 390px;
          height: 30px;
          padding-left: 10px;
        }

        textarea {
          width: 390px;
          padding: 10px 2px 10px 10px;
          resize: none;
          font-family: sans-serif;
          font-size: 12px;
        }

        &:nth-child(5) {
          height: 404px;
          margin-bottom: 5px;
          display: flex;
          justify-content: left;
          align-items: center;
        }
      }

      .view-password {
        position: absolute;
        right: 10px;
        cursor: pointer;
        user-select: none;
      }

      .introduce-code {
        position: absolute;
        right: -30px;
        top: 7px;
        width: 20px;
        height: 20px;
        border: 1px solid #ccc;
        border-radius: 50%;
        white-space: nowrap;
        text-align: center;
        text-decoration: none;
        line-height: 20px;
        color: #ccc;
        font-size: 12px;
        font-weight: bold;
      }
    }

    & > div:last-child {
      width: 504px;
      display: flex;
      justify-content: flex-end;

      button {
        &:first-child {
          margin-right: 15px;
        }
        width: 38.6%;
        height: 30px;

        &.w100 {
          width: 404px;
          margin-right: 0;
        }
      }
    }
  }
}

.main-content .message {
  position: absolute;
  bottom: -30px;
  opacity: 0;
  left: 50%;
  padding: 10px 16px;
  border-radius: 5px;
  font-weight: bold;
  transform: translateX(-50%);
  transition: 0.5s;
  background: #fff;
  box-shadow: 0 0 5px #ccc;

  &--active {
    animation: show ease 2s forwards;
  }

  @keyframes show {
    0%,
    100% {
      opacity: 0;
      bottom: -30px;
    }

    40%,
    60% {
      opacity: 1;
      bottom: 30px;
    }
  }
}

.main-content .close {
  position: absolute;
  right: 10px;
  top: 10px;
  width: 22px;
  height: 22px;
  overflow: hidden;
  cursor: pointer;

  &:hover {
    div {
      background: #666;
    }
  }

  div {
    position: absolute;
    left: -10%;
    top: 10px;
    width: 120%;
    height: 2px;
    background: #ccc;
    transform: rotate(45deg);
    transition: 0.5s;

    &:last-child {
      transform: rotate(-45deg);
    }
  }
}</style
>>
